<template>
  <view class="study-plan-container">
        <v-statusbar class="status-bar"></v-statusbar>

    <!-- 页面头部 -->
    <view class="header">
      <view class="header-left">
        <view class="back-btn" @click="navigateBack">
          <uni-icons type="left" size="24"></uni-icons>
        </view>
        <view class="page-title">个性化课后学习计划</view>
      </view>
    </view>

    <!-- 计划概览 -->
    <view class="plan-overview">
      <view class="overview-progress">
        <!-- 饼图展示任务完成情况 -->
        <view class="pie-chart">
          <qiun-data-charts type="pie" :chartData="pieChartData" :opts="pieChartOpts" />
        </view>
        <view class="progress-info">
          <view class="progress-title">今日任务完成情况</view>
          <view class="progress-stats">
            <view class="stat-item">
              <text class="stat-value">{{ completedTasksCount }}</text>
              <text class="stat-label">个已完成</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ consecutiveDays }}</text>
              <text class="stat-label">天连续打卡</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ totalDays }}</text>
              <text class="stat-label">天总共打卡</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 今日任务 -->
    <view class="today-tasks-section">
      <view class="section-header">
        <view class="section-title">今日任务</view>
        <view class="section-date">{{ currentDate }}</view>
      </view>
      <!-- 任务列表和遮罩需要放在一个相对定位的容器中 -->
      <view class="tasks-container">
        <view class="tasks-list">
          <view v-for="(task, index) in todayTasks" :key="task.id || index" class="task-item"
            :class="{ completed: task.status === 1 }" @click="toggleTaskCompletion(index)">
            <view class="task-checkbox">
              <view class="checkbox-inner" :class="{ checked: task.status === 1 }"></view>
            </view>
            <view class="task-content">
              <view class="task-title">{{ task.title }}</view>
              <view class="task-meta">
                <view class="task-duration">预计学习时间：{{ task.estimatedTime }}</view>
                <view class="task-priority" :class="getPriorityClass(task.difficulty)">
                  {{ task.difficulty }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 添加遮罩层 -->
        <view class="tasks-mask" v-if="showTasksMask">
          <view class="mask-content">
            <view class="mask-icon">
              <image src="/static/image/AI/missionSuccess.png" mode="aspectFit"></image>
            </view>
            <view class="mask-title">恭喜你，今日任务已全部完成！</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 学习建议 -->
    <view class="recommendations-section">
      <view class="section-header">
        <view class="section-title">AI建议</view>
      </view>
      <view class="recommendation-content">
        <view class="recommendation-icon">
          <image src="/static/image/logo.png" mode="aspectFit"></image>
        </view>
        <view class="recommendation-text">
          {{ aiRecommendation }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mixins from '@/mixins'

export default {
  mixins: [mixins],
  name: 'study-plan',
  data() {
    return {
      currentDate: '',
      pieChartData: {}, // 饼图数据
      pieChartOpts: {}, // 饼图配置
      consecutiveDays: '',
      totalDays: '',
      todayTasks: [],
      aiRecommendation: '正在生成中...',
      showTasksMask: false 
    }
  },
  // 在 computed 部分添加一个新的计算属性
  computed: {
    // 计算今日任务完成率
    todayTaskCompletionRate() {
      const completedCount = this.todayTasks.filter(task => task.status === 1).length
      return Math.round((completedCount / (this.todayTasks.length || 1)) * 100)
    },
    // 计算已完成任务数量
    completedTasksCount() {
      return this.todayTasks.filter(task => task.status === 1).length
    },
    // 判断是否所有任务都已完成
    isAllTasksCompleted() {
      // 如果没有任务，返回 false
      if (this.todayTasks.length === 0) {
        return false
      }
      // 检查是否所有任务的状态都是已完成(1)
      return this.todayTasks.every(task => task.status === 1)
    }
  },
  onLoad() {
    this.initData()
    this.loadAllData() // 统一加载所有数据
  },
  methods: {
    // 初始化数据
    initData() {
      // 设置当前日期
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      this.currentDate = `${year}-${month}-${day}`
    },

    // 统一加载所有数据
    async loadAllData() {
      try {
        // 并行加载打卡数据和学习计划数据
        await Promise.all([
          this.loadAttendanceData(),
          this.generateTodaySchedule()
        ])
        // 加载数据后检查任务是否全部完成
        this.updateTasksMaskVisibility()
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },

    // 更新任务状态后也需要检查
    async toggleTaskCompletion(index) {
      const task = this.todayTasks[index]
      try {
        // 这里应该有一个API调用来更新任务状态
        const res = await this.$axios.post('/schedule/finish', { id: task.id })
        if (res == "修改成功") {
          // 更新本地任务状态
          this.todayTasks[index].status = task.status === 1 ? 0 : 1
          // 更新饼图数据
          this.initPieChart()
          // 检查任务是否全部完成
          this.updateTasksMaskVisibility()
        } else {
          this.showMessage.error('更新状态失败，请稍后重试')
        }
        // 更新饼图数据
        this.initPieChart()
        this.loadAttendanceData()
      } catch (error) {
        console.error('更新任务状态失败:', error)
        this.showMessage.error('更新状态失败，请稍后重试')
      }
    },

    // 添加一个更新遮罩可见性的方法
    updateTasksMaskVisibility() {
      this.showTasksMask = this.isAllTasksCompleted
    },
    // 初始化饼图
    initPieChart() {
      // 准备饼图数据 - 基于今日任务完成情况
      const completedCount = this.todayTasks.filter(task => task.status === 1).length
      const totalCount = this.todayTasks.length

      this.pieChartData = {
        series: [
          {
            name: '已完成',
            data: completedCount
          },
          {
            name: '未完成',
            data: totalCount - completedCount
          }
        ]
      }

      this.pieChartOpts = {
        color: ['#476bff', '#e8f3ff'],
        padding: [5, 5, 5, 5],
        enableScroll: false,
        extra: {
          pie: {
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: true,
            borderWidth: 3,
            borderColor: "#FFFFFF"
          }
        }
      }
    },

    // 生成今日任务
    async generateTodaySchedule() {
      try {
        const res = await this.$axios.get('/ai/generate/schedule')
        if (res) {
          this.aiRecommendation = res
          // 生成成功后加载任务列表
          await this.loadStudyPlanData()
        } else {
          // 即使已经生成过，也加载任务列表
          await this.loadStudyPlanData()
          // 如果有错误消息则显示
          if (res && res.msg) {
            this.showMessage.info(res.msg)
          }
        }
      } catch (error) {
        console.error('生成今日任务失败:', error)
        this.showMessage.error('生成任务失败，请稍后重试')
        await this.loadStudyPlanData()
      }
    },

    // 加载学习计划数据
    async loadStudyPlanData() {
      try {
        const res = await this.$axios.get('/schedule/list/me')
        if (res && res[this.currentDate]) {
          // 从返回数据中获取今日任务
          this.todayTasks = res[this.currentDate]
          // 重新初始化饼图
          this.initPieChart()
        } else {
          // 没有任务数据时设置默认值
          this.todayTasks = []
          this.initPieChart()
        }
      } catch (error) {
        console.error('加载学习计划数据失败:', error)
        this.showMessage.error('加载数据失败，请稍后重试')
      }
    },

    // 返回上一页
    navigateBack() {
      this.toPage(-1)
    },

    // 获取打卡数据
    async loadAttendanceData() {
      try {
        const res = await this.$axios.get('/attendance')
        if (res) {
          this.consecutiveDays = res.consecutiveDays
          this.totalDays = res.totalDays
        } else {
          this.consecutiveDays = "--"
          this.totalDays = "--"
        }
      } catch (error) {
        console.error('加载打卡数据失败:', error)
        this.showMessage.error('加载打卡数据失败，请稍后重试')
        // 设置默认值
        this.consecutiveDays = "--"
        this.totalDays = "--"
      }
    },

    // 根据难度获取优先级样式类
    getPriorityClass(difficulty) {
      switch (difficulty) {
        case '简单':
          return 'low'
        case '中等':
          return 'medium'
        case '困难':
          return 'high'
        default:
          return 'medium'
      }
    },

    // 切换任务完成状态
    async toggleTaskCompletion(index) {
      const task = this.todayTasks[index]
      try {
        // 这里应该有一个API调用来更新任务状态
        const res = await this.$axios.post('/schedule/finish', { id: task.id })
        if (res == "修改成功") {
          // 更新本地任务状态
          this.todayTasks[index].status = task.status === 1 ? 0 : 1
          // 更新饼图数据
          this.initPieChart()
          this.updateTasksMaskVisibility()
        } else {
          this.showMessage.error('更新状态失败，请稍后重试')
        }
        // 更新饼图数据
        this.initPieChart()
        this.loadAttendanceData()
      } catch (error) {
        console.error('更新任务状态失败:', error)
        this.showMessage.error('更新状态失败，请稍后重试')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../basis.scss";

.study-plan-container {
  min-height: 100vh;
  background-color: #f8f9ff;

  .header {
    height: 100rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;

    .header-left {
      display: flex;
      align-items: center;

      .back-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 20rpx;
      }

      .page-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
  }

  .plan-overview {
    padding: 30rpx;
    background-color: #fff;
    margin-top: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .overview-progress {
      display: flex;
      align-items: center;
      justify-content: space-evenly;

      .pie-chart {
        position: relative;
        width: 60%;
        height: 300rpx;
      }

      .progress-info {
        .progress-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 20rpx;
        }

        .progress-stats {
          display: flex;
          flex-direction: column;

          .stat-item {
            position: relative;
            display: inline-block;
            padding-right: 70rpx;
            margin-bottom: 10rpx;
            min-width: 150rpx;

            .stat-value {
              font-size: 40rpx;
              font-weight: bold;
              color: #476bff;
              display: inline-block;
              padding-right: 10rpx;
            }

            .stat-label {
              font-size: 24rpx;
              color: #999;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
    }
  }

  .today-tasks-section {
    padding: 30rpx;
    background-color: #fff;
    margin-top: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .section-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }

      .section-date {
        font-size: 24rpx;
        color: #999;
      }
    }

    // 任务容器，用于定位遮罩
    .tasks-container {
      position: relative;
      width: 100%;
      min-height: 100rpx; // 确保即使没有任务也有基础高度
    }

    .tasks-list {
      display: flex;
      flex-direction: column;
      gap: 20rpx;

      .task-item {
        display: flex;
        align-items: center;
        padding: 24rpx;
        border: 2rpx solid #f0f0f0;
        border-radius: 12rpx;
        transition: all 0.3s ease;

        &:hover {
          border-color: #476bff;
          box-shadow: 0 4rpx 12rpx rgba(71, 107, 255, 0.1);
        }

        &.completed {
          opacity: 0.7;
        }

        .task-checkbox {
          width: 40rpx;
          height: 40rpx;
          border: 2rpx solid #ddd;
          border-radius: 50%;
          margin-right: 20rpx;
          display: flex;
          justify-content: center;
          align-items: center;

          .checkbox-inner {
            width: 24rpx;
            height: 24rpx;
            border-radius: 50%;
            background-color: transparent;
          }

          .checkbox-inner.checked {
            background-color: #476bff;
          }
        }

        .task-content {
          flex: 1;

          .task-title {
            font-size: 26rpx;
            color: #333;
            margin-bottom: 8rpx;
          }

          .task-meta {
            display: flex;
            align-items: center;
            gap: 20rpx;

            .task-duration {
              font-size: 22rpx;
              color: #999;
            }

            .task-priority {
              font-size: 20rpx;
              padding: 4rpx 16rpx;
              border-radius: 12rpx;
              color: #fff;

              &.high {
                background-color: #ff6b6b;
              }

              &.medium {
                background-color: #ffd166;
              }

              &.low {
                background-color: #06d6a0;
              }
            }
          }
        }
      }
    }

    // 任务列表遮罩样式
    .tasks-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      border-radius: 12rpx;
      z-index: 10;
      display: flex;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(4rpx); // 添加模糊效果
      animation: fadeIn 0.5s ease;
    }

    // 遮罩内容样式
    .mask-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-color: #fff;
      padding: 60rpx 40rpx;
      border-radius: 24rpx;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
      animation: scaleIn 0.5s ease;
    }

    // 图标容器样式
    .mask-icon {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      background-color: #f0f7ff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 30rpx;
      animation: pulse 2s infinite;

      image {
        width: 100rpx;
        height: 100rpx;
      }
    }

    // 标题样式
    .mask-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #476bff;
      text-align: center;
      animation: slideUp 0.6s ease;
    }

    // 动画效果
    @keyframes fadeIn {
      from {
        opacity: 0;
      }

      to {
        opacity: 1;
      }
    }

    @keyframes scaleIn {
      from {
        transform: scale(0.9);
        opacity: 0;
      }

      to {
        transform: scale(1);
        opacity: 1;
      }
    }

    @keyframes slideUp {
      from {
        transform: translateY(20rpx);
        opacity: 0;
      }

      to {
        transform: translateY(0);
        opacity: 1;
      }
    }

    @keyframes pulse {
      0% {
        box-shadow: 0 0 0 0 rgba(71, 107, 255, 0.4);
      }

      70% {
        box-shadow: 0 0 0 20rpx rgba(71, 107, 255, 0);
      }

      100% {
        box-shadow: 0 0 0 0 rgba(71, 107, 255, 0);
      }
    }
  }

  .recommendations-section {
    padding: 30rpx;
    background-color: #fff;
    margin-top: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .section-header {
      margin-bottom: 24rpx;

      .section-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .recommendation-content {
      display: flex;
      align-items: flex-start;
      padding: 24rpx;
      background-color: #f8f9ff;
      border-radius: 16rpx;

      .recommendation-icon {
        width: 80rpx;
        height: 80rpx;
        background-color: #e6f3ff;
        border-radius: 12rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 20rpx;
        flex-shrink: 0;

        image {
          width: 70rpx;
          height: 70rpx;
        }
      }

      .recommendation-text {
        flex: 1;
        font-size: 24rpx;
        color: #666;
        line-height: 1.6;
      }
    }
  }
}
</style>